import router from '@/gov/router'
import constantRoutes from '@/gov/router/constantRoutes'
import commonRoutes from '@/gov/router/commonRoutes'
import asyncRoutes from '@/gov/router/busRoutes'
import { getData } from '@vimi/utils-api'

const menuPath = [
  '/credit/import/xinnong',
  '/credit/recom',
  '/credit/register',
  '/credit/track',
  '/credit/data/ic',
  '/credit/data/family',
  '/credit/data/scale',
  '/credit/data/insurance',
  '/credit/data/subsidy',
  '/credit/data/power',
  '/credit/data/machinery',
]
export const hasPermission = (userJob, userOrg, scopeArr, route) => {
  if (route.meta) {
    const { job, org, scope } = route.meta
    return (
      (!job || job.includes(userJob)) &&
      (!org || org.includes(userOrg)) &&
      (!scope || scopeArr.includes(scope))
    )
  } else {
    return true
  }
}

// 递归过滤异步路由表，返回符合用户角色权限的路由表
const filterAsyncRouter = (routes, job, org, scopeArr, mainBusiness, menuList, pth) => {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(job, org, scopeArr, route)) {
      if (tmp.children) {
        tmp.children = filterAsyncRouter(tmp.children, job, org, scopeArr, mainBusiness, menuList, [
          ...pth,
          tmp.path,
        ])
      }
      const allPath = [...pth, tmp.path].join('/').replace('/', '')
      if (menuPath.includes(allPath)) {
        if (menuList.includes(allPath)) {
          res.push(tmp)
        }
      } else if ((tmp?.meta?.name ?? '') === 'govApproval') {
        const business = menuList.filter(item => item.includes('/credit/import/class?i='))
        for (let p of business) {
          const a = p.split('?i=')
          if (a.length > 1) {
            tmp.children.unshift({
              path: `class?i=${a[1]}`,
              meta: { title: mainBusiness[a[1]] },
            })
          }
        }
        if (tmp.children.length > 1) {
          if (tmp.children.length === 2 && tmp.children[1].name === 'import_xinnong') {
            tmp.redirect = { name: 'import_xinnong' }
          } else if (tmp.children[0].path.includes('class?i=')) {
            const a = tmp.children[0].path.split('?i=')
            let redirectQuery = ''
            if (a.length > 1) {
              redirectQuery = a[1]
            }
            tmp.redirect = { name: 'import_class', query: { i: redirectQuery } }
          } else {
            tmp.redirect = { name: 'import_class' }
          }
          res.push(tmp)
        }
      } else if (tmp.name === 'data_index') {
        if (tmp.children.length > 0) {
          tmp.redirect = { name: tmp.children[0].name }
          res.push(tmp)
        }
      } else {
        res.push(tmp)
      }
    }
  })

  return res
}

// 无 '/' 根路由，需要添加并重定向到第一个路由
const addRootRoute = routes => {
  if (routes.some(item => item.path === '/') || !routes.length) {
    return routes
  }
  routes.unshift({
    path: '/',
    redirect: routes[0].path,
  })

  return routes
}

const addCommonRoute = routes => {
  return new Promise((resolve, reject) => {
    if (!routes || !routes.length) {
      return reject(router)
    }

    let child = []
    for (const route of routes) {
      if (route.children) {
        child = route
        break
      }
    }

    // 异步路由不存在（可能是由于已登录，但没有权限）
    if (!child.children) {
      return reject(router)
    }
    for (const r of child.children) {
      if (r.children) {
        r.children.push.apply(r.children, commonRoutes)
        break
      }
    }

    resolve(routes)
  })
}

const state = {
  routes: constantRoutes,
  asyncRoutes: [],
}
const getters = {
  routes: state => state.routes,
  asyncRoutes: state => state.asyncRoutes,
}
const actions = {
  async generateRoutes({ commit, rootGetters }, data) {
    const { job, clientOrgClass, scopeArr, userId } = data
    const menuRes = await getData('credit', 'menu_config_user', { 'user_id.eq': userId })
    const resData = menuRes?.data?.[0] ?? {}
    const menuList = resData?.menu_key?.split('|') ?? []
    let accessedRouters = filterAsyncRouter(
      asyncRoutes,
      job,
      clientOrgClass,
      scopeArr,
      rootGetters.provinceMainBusinessEnum,
      menuList,
      []
    )
    accessedRouters = addRootRoute(accessedRouters)
    return addCommonRoute(accessedRouters).then(res => {
      accessedRouters = [...res]
      commit('setRoutes', accessedRouters)
      accessedRouters.forEach(r => router.addRoute(r))
    })
  },
}
const mutations = {
  setRoutes: (state, payload) => {
    state.asyncRoutes = payload
    state.routes = constantRoutes.concat(payload)
  },
}

export default {
  state,
  getters,
  actions,
  mutations,
}
